//
//  UIView+DebugManager.m
//  YK_DebugManager
//
//  Created by edward on 2021/11/30.
//

#import "UIView+DebugManager.h"
#import <objc/runtime.h>
#import "DebugManagerUtil.h"

@interface UIView ()

@property (nonatomic ,strong) CALayer *debug_metricsBorderLayer;

@end

@implementation UIView (DebugManager)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
    });
}

- (void)debugManager_layoutSubviews
{
    [self debugManager_layoutSubviews];
    [self debug_MetricsRecursiveEnable:[DebugManagerUtil sharedInstance].debug_borderShow];
}

- (void)debug_MetricsRecursiveEnable:(BOOL)enable
{
    // 状态栏不显示元素边框
    
    if (@available(iOS 16.0, *)) {
        
    } else {
        UIWindow *statusBarWindow = [[UIApplication sharedApplication] valueForKey:@"_statusBarWindow"];
        if (statusBarWindow && [self isDescendantOfView:statusBarWindow]) {
            return;
        }
    }
    

    for (UIView *subView in self.subviews) {
        [subView debug_MetricsRecursiveEnable:enable];
    }
    
    if (enable) {
        if (!self.debug_metricsBorderLayer) {
            UIColor *borderColor = [self ramdomColor];
            self.debug_metricsBorderLayer = ({
                CALayer *layer = CALayer.new;
                layer.borderWidth = 1;
                layer.borderColor = borderColor.CGColor;
                layer;
            });
            [self.layer addSublayer:self.debug_metricsBorderLayer];
        }
        
        self.debug_metricsBorderLayer.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
        self.debug_metricsBorderLayer.hidden = NO;
    } else if (self.debug_metricsBorderLayer) {
        self.debug_metricsBorderLayer.hidden = YES;
    }
}

- (void)setDebug_metricsBorderLayer:(CALayer *)debug_metricsBorderLayer
{
    objc_setAssociatedObject(self, @selector(debug_metricsBorderLayer), debug_metricsBorderLayer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (CALayer *)debug_metricsBorderLayer
{
    return objc_getAssociatedObject(self, _cmd);
}

- (UIColor *)ramdomColor
{
    return [UIColor colorWithRed:(arc4random_uniform(255.0))/255.0 green:( arc4random_uniform(255.0))/255.0 blue:(arc4random_uniform(255.0))/255.0 alpha:1.0];
}


@end
